package com.ygnn.task;

import com.ygnn.common.Vo.OrderVo;
import com.ygnn.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.*;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.interactions.Actions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.File;

import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * ClassName:SubmitOrderTask
 * Package:com.ygnn.task
 * Description:
 *
 * @Author: dlh
 * @Creat:2024/10/16-14:02
 */
@Service
@Slf4j
public class SubmitOrderTask {
    @Autowired
    private OrderService orderService;
    static int[] weekDay = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5};

//    @Scheduled(fixedRate = 300000)
    public void runTaskEveryMinute() {
//        ClassLoader classLoader = Example.class.getClassLoader();
//        URL resourceUrl = classLoader.getResource("msedgedriver.exe");
//        File file = new File(resourceUrl.getFile());
        File file = new File("C:\\lepao_slim\\slem\\src\\main\\resources\\msedgedriver.exe");
        System.setProperty("webdriver.edge.driver", file.getAbsolutePath());
        //打开网站
        WebDriver driver = new EdgeDriver();
        //放大页面
        driver.manage().window().maximize();
        // 1、登录网站
        driver.get("https://www.yjer.buzz/jiuzhuandachang/#/login?redirect=%2Fdashboard");

        // 定位用户名密码
        WebElement nid = driver.findElement(By.name("phone"));
        WebElement pid = driver.findElement(By.name("password"));

        // 输入用户名密码
        String name = "19582082411";
        String password = "dlh108108713";
        nid.sendKeys(name);
        pid.sendKeys(password);

        // 模拟点击登录
        WebElement button = driver.findElement(By.xpath("/html/body/div/div/form/button"));
        button.click();
        Sleep(10000);

        //2.点击订单管理
        WebElement order = driver.findElement(By.xpath("/html/body/div/div/div[1]/div/div[1]/div/ul/div[3]/a"));
        order.click();
        Sleep(10000);

        //从数据库查询
        List<OrderVo> orderVos = orderService.selectAll();
        for (OrderVo orderVo : orderVos) {
            // 3、点击出现下拉菜单
            // 移动到新增订单
            WebElement noButton = driver.findElement(By.xpath("/html/body/div/div/div[2]/section/div/div[1]/form/div/div[8]/button"));
            Actions actions = new Actions(driver);
            actions.moveToElement(noButton).perform();
            Sleep(1000);
            // 移动到步道健身，并点击
            java.util.List<WebElement> btns = driver.findElements(By.cssSelector("li[class*='el-dropdown-menu__item']"));
            int cnt = 0;
            for (WebElement b : btns) {
                if (cnt == 5) {
                    b.click();
                    Sleep(1000);
                    break;
                }
                cnt++;
            }

            // 打开新增订单窗口
            // 输入查询id
            WebElement inid = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div/div/div[2]/form/div[1]/div/div/input"));
            String userId = String.valueOf(orderVo.getUserId());
            inid.sendKeys(userId);
            // 点击查询按钮
            WebElement qbtn = driver.findElement(By.cssSelector("button[class='el-button el-button--default el-button--mini']"));
            qbtn.click();
            Sleep(1500);
            //判断id是否有问题
            int devCnt = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[2]/div[1]/form[2]")).findElements(By.cssSelector("div")).size();
            if (devCnt < 1) {
                //没授权
                log.info("{}未授权或id有误", orderVo.getUserId());
                orderService.upDateById(orderVo.getUserId(), -1, "未授权或id有误");
                // 刷新页面
                driver.navigate().refresh();
                Sleep(2000);
                continue;
            }
            //判断是否是大一大二的界面
            WebElement parentDiv = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div/div/div[2]/form/div[3]/div"));
            List<WebElement> childDivs = parentDiv.findElements(By.cssSelector("div"));
            if (childDivs.size() >= 3) {
                //是大一大二的界面
                try {
                    if (orderVo.getKm() == 1) {
                        //下单早操：
                        WebElement km = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div/div/div[2]/form/div[3]/div/div/div/input"));
                        km.clear();
                        km.sendKeys("1.0");
                        //设置尽量早于7：00
                        driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[2]/div[1]/form[1]/div[2]/div/label/span[1]/span")).click();
                        WebElement jieZhitime = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[2]/div[1]/form[1]/div[2]/div/div/input"));
                        jieZhitime.clear();
                        jieZhitime.sendKeys("06:30");
                        // 按下回车键
                        jieZhitime.sendKeys(Keys.RETURN);
                        //设置开始日期
                        String startTime = new SimpleDateFormat("yyyy-MM-dd").format(orderVo.getStartDate());
                        WebElement start = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[2]/div[1]/form[2]/div/div[2]/div[2]/div/div/input"));
                        start.clear();
                        start.sendKeys(startTime);
                        driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[1]/div/span[1]")).click();

                        //设置次数
                        String cizhu = String.valueOf(orderVo.getTimes());
                        WebElement cnts = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[2]/div[1]/form[2]/div/div[2]/div[3]/div/div/div/input"));
                        cnts.clear();
                        cnts.sendKeys(cizhu);
                        driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[1]/div/span[1]")).click();
                        //取消勾选周六日
                        driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[2]/div[1]/form[2]/div/div[2]/div[4]/div/div/label[6]/span[1]")).click();
                        driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[2]/div[1]/form[2]/div/div[2]/div[4]/div/div/label[7]/span[1]")).click();
                    } else {
                        //下单课外跑
                        //设置尽量早于22：00
                        driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[2]/div[1]/form[1]/div[2]/div/label/span[1]/span")).click();
                        WebElement jieZhitime = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[2]/div[1]/form[1]/div[2]/div/div/input"));
                        jieZhitime.clear();
                        jieZhitime.sendKeys("22:00");
                        // 按下回车键
                        jieZhitime.sendKeys(Keys.RETURN);
                        //取消勾选晨跑&&勾选课外跑
                        driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[2]/div[1]/form[2]/div/div[2]/div[1]/div/div[1]/label/span[1]/span")).click();
                        driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[2]/div[1]/form[2]/div/div[2]/div[1]/div/div[2]/label/span[1]/span")).click();
                        //设置开始时间
                        String startTime = new SimpleDateFormat("yyyy-MM-dd").format(orderVo.getStartDate());
                        WebElement start = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[2]/div[1]/form[2]/div/div[2]/div[2]/div/div/input"));
                        start.clear();
                        start.sendKeys(startTime);
                        driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[1]/div/span[1]")).click();
                        //设置次数
                        String cizhu = String.valueOf(orderVo.getTimes());
                        WebElement cnts = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[2]/div[1]/form[2]/div/div[2]/div[3]/div/div/div/input"));
                        cnts.clear();
                        cnts.sendKeys(cizhu);
                        driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[1]/div/span[1]")).click();
                        //一周内只勾选两天
                        int zhouJi = weekDay(startTime) + 2;//开始时间是周几
                        int flag = 0;
                        while (flag != 5) {
                            //取消勾选五天
                            driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[2]/div[1]/form[2]/div/div[2]/div[4]/div/div/label[" + (weekDay[zhouJi++]) + "]/span[1]")).click();
                            flag++;
                        }
                    }
                    //先更改用户状态
                    orderService.upDateById(orderVo.getUserId(), 1, "下单成功");
                    //再点击提交：
                    driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[2]/div[2]/button/span")).click();
                    Sleep(1000);
                    log.info("用户{}已成功下单{}次", orderVo.getUserId(), orderVo.getTimes());
                } catch (Exception e) {
                    orderService.upDateById(orderVo.getUserId(), 0, "未知错误");
                }
                // 刷新页面
                driver.navigate().refresh();
                Sleep(2000);
            } else {
                try {

                    //大三大四的界面
                    //设置尽量早于22：00
                    driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[2]/div[1]/form[1]/div[2]/div/label/span[1]/span")).click();
                    WebElement jieZhitime = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[2]/div[1]/form[1]/div[2]/div/div/input"));
                    jieZhitime.clear();
                    jieZhitime.sendKeys("22:00");
                    // 按下回车键
                    jieZhitime.sendKeys(Keys.RETURN);
                    //设置开始时间
                    String startTime = new SimpleDateFormat("yyyy-MM-dd").format(orderVo.getStartDate());
                    WebElement start = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[2]/div[1]/form[2]/div/div[2]/div[2]/div/div/input"));
                    start.clear();
                    start.sendKeys(startTime);
                    driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[1]/div/span[1]")).click();
                    //设置次数
                    String cizhu = String.valueOf(orderVo.getTimes());
                    WebElement cnts = driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[2]/div[1]/form[2]/div/div[2]/div[3]/div/div/div/input"));
                    cnts.clear();
                    cnts.sendKeys(cizhu);
                    driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[1]/div/span[1]")).click();
                    //一周内只勾选两天
                    int zhouJi = weekDay(startTime) + 2;//开始时间是周几
                    int flag = 0;
                    while (flag != 5) {
                        //取消勾选五天
                        driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[2]/div[1]/form[2]/div/div[2]/div[4]/div/div/label[" + (weekDay[zhouJi++]) + "]/span[1]")).click();
                        flag++;
                    }
                    //先更改用户状态
                    orderService.upDateById(orderVo.getUserId(), 1, "下单成功");
                    //点击提交：
                    driver.findElement(By.xpath("/html/body/div[1]/div/div[2]/section/div/div[4]/div[1]/div/div[2]/div[2]/button/span")).click();
                    Sleep(1000);
                    log.info("用户{}已成功下单{}次3km", orderVo.getUserId(), orderVo.getTimes());
                } catch (Exception e) {
                    orderService.upDateById(orderVo.getUserId(), 0, "未知错误");
                }
                // 刷新页面
                driver.navigate().refresh();
                Sleep(2000);
            }
        }
        log.info("已全部完成");
        // 关闭浏览器
        driver.quit();
    }

    public static void Sleep(int sleep) {
        try {
            Thread.sleep(sleep);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //判断开始时间是周几
    public static int weekDay(String time) {
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 将字符串转换为LocalDate对象
        LocalDate date = LocalDate.parse(time, formatter);
        // 获取星期几
        DayOfWeek dayOfWeek = date.getDayOfWeek();
        // 将星期几转换为数字
        return dayOfWeek.getValue(); // 星期一到星期天分别为1到7
    }
}
